package com.rongx.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongx.reggie.common.BaseContext;
import com.rongx.reggie.entity.AddressBook;
import com.rongx.reggie.mapper.AddressBookMapper;
import com.rongx.reggie.service.AddressBookService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 地址簿服务实现类
 * 提供地址簿的增删改查等业务逻辑处理
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    /**
     * 保存地址信息并关联当前用户
     *
     * @param addressBook 地址信息
     */
    @Override
    public void saveWithUserId(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        this.save(addressBook);
    }

    /**
     * 设置默认地址
     * 先将用户的所有地址设为非默认，再将指定地址设为默认
     *
     * @param addressBook 要设为默认的地址信息
     */
    @Override
    public void setDefault(AddressBook addressBook) {
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        wrapper.set(AddressBook::getIsDefault, 0);
        //SQL:update address_book set is_default = 0 where user_id = ?
        this.update(wrapper);

        addressBook.setIsDefault(1);
        //SQL:update address_book set is_default = 1 where id = ?
        this.updateById(addressBook);
    }

    /**
     * 获取当前用户的默认地址
     *
     * @return 默认地址信息，若不存在则返回null
     */
    @Override
    public AddressBook getDefault() {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        queryWrapper.eq(AddressBook::getIsDefault, 1);
        return this.getOne(queryWrapper);
    }

    /**
     * 获取指定用户的地址列表
     *
     * @param addressBook 包含用户ID的地址对象
     * @return 用户的地址列表
     */
    @Override
    public List<AddressBook> getList(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != addressBook.getUserId(),AddressBook::getUserId, addressBook.getUserId());
        queryWrapper.orderByDesc(AddressBook::getUpdateTime);
        return this.list(queryWrapper);
    }
}
